package main

import (
	"fmt"
	"os"

	"github.com/spf13/cobra"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"

	"go-war3proxy/pkg/client"
	"go-war3proxy/pkg/server"
)

var (
	logger *zap.Logger
)

func main() {
	// 初始化日志
	logger = initLogger()
	defer logger.Sync()

	// 创建根命令
	rootCmd := &cobra.Command{
		Use:   "go-war3proxy",
		Short: "War3代理服务器和客户端",
		Long:  `War3代理服务器和客户端，用于在互联网上玩魔兽争霸3局域网游戏`,
	}

	// 添加子命令
	rootCmd.AddCommand(server.NewServerCommand(logger))
	rootCmd.AddCommand(client.NewClientCommand(logger))

	// 执行命令
	if err := rootCmd.Execute(); err != nil {
		fmt.Fprintf(os.Stderr, "错误: %v\n", err)
		os.Exit(1)
	}
}

// initLogger 初始化日志记录器
func initLogger() *zap.Logger {
	// 配置日志编码器
	encoderConfig := zapcore.EncoderConfig{
		TimeKey:        "time",
		LevelKey:       "level",
		NameKey:        "logger",
		CallerKey:      "caller",
		FunctionKey:    zapcore.OmitKey,
		MessageKey:     "msg",
		StacktraceKey:  "stacktrace",
		LineEnding:     zapcore.DefaultLineEnding,
		EncodeLevel:    zapcore.CapitalColorLevelEncoder,
		EncodeTime:     zapcore.ISO8601TimeEncoder,
		EncodeDuration: zapcore.SecondsDurationEncoder,
		EncodeCaller:   zapcore.ShortCallerEncoder,
	}

	// 配置日志核心
	core := zapcore.NewCore(
		zapcore.NewConsoleEncoder(encoderConfig),
		zapcore.AddSync(os.Stdout),
		zapcore.InfoLevel,
	)

	// 创建日志记录器
	return zap.New(core, zap.AddCaller(), zap.AddCallerSkip(0))
}
